package xiangya.bysj.service.impl;

import java.util.List;

import javax.annotation.Resource;

import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import com.taobao.api.domain.Userinfos;

import xiangya.bysj.entity.User;
import xiangya.bysj.mapper.interf.UserMapper;
import xiangya.bysj.service.interf.UserServiceInterface;

/**
 * 普通用户业务类
 * 
 * @author lbj
 *
 */
@Service("userService")
@Transactional(readOnly = false, rollbackFor = Exception.class, propagation = Propagation.REQUIRED)
public class UserServiceImpl implements UserServiceInterface {

	/**
	 * imopen服务类
	 */
	@Resource
	private IMServiceImpl imservice;

	@Resource
	private UserMapper userMapper;

	/**
	 * 普通用户注册
	 */
	@Override
	public void save(User obj) throws Exception {

		/**
		 * 创建imopen账号 并向imopen添加账号信息 为客户端聊天做准备
		 */
		Userinfos userInfo = new Userinfos();
		userInfo.setUserid(obj.getUserAccount());// 登陆账号
		userInfo.setPassword(obj.getUserPass());// 用户密码
		userInfo.setNick(obj.getUserName()); // 昵称

		/**
		 * 保存在阿里im服务器
		 */
		imservice.save(userInfo);

		/**
		 * 保存在本地服务器
		 */
		userMapper.save(obj);

	}

	/**
	 * 普通用户修改信息 只限password
	 */
	@Override
	public void update(User obj) throws Exception {

		userMapper.update(obj);

		Userinfos userInfo = new Userinfos();
		userInfo.setUserid(obj.getUserAccount());
		userInfo.setPassword(obj.getUserPass());

		imservice.update(userInfo);

	}

	/**
	 * 删除
	 */
	@Override
	public void delete(int objId) throws Exception {
		userMapper.delete(objId);
	}

	/**
	 * 普通用户登陆
	 */
	@Override
	public User login(String account, String password) throws Exception {

		User user = userMapper.selectByAccount(account);

		if (user != null && user.getUserPass() != null) {
			if (!user.getUserPass().equals(password))
				user = null;
		}

		return user;
	}

	/**
	 * 找回密码
	 */
	@Override
	public User findPasswordByPhone(String phone) throws Exception {

		User user = userMapper.selectByPhone(phone);

		return user;
	}

	@Override
	public User findUserByAccount(String account) throws Exception {

		return userMapper.selectByAccount(account);
	}

	@Override
	public List<User> findByName(String name) throws Exception {
		return userMapper.selectByName(name);
	}

	public List<User> selectUser() {
		return userMapper.selectUser();
	}

}
